/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.commons.i18n;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.geoscheduler.commons.tools.AssertTools;
import org.geoscheduler.commons.tools.StringTools;

/**
 * 
 * <h2>AbstractLocalizationSource</h2>
 * <p>
 * Abstract implementation {@link LocalizationSource} implementing basic
 * translation logic using {@link ResourceBundle} API. If
 * {@link MissingResourceException} occurs default value is used.
 * </p>
 * <p>
 * Class is intended to be extended by localization source implementations.
 * </p>
 * 
 * @author LKo (Lukas.Kolisko@Geoscheduler.org)
 */
public abstract class AbstractLocalizationSource implements LocalizationSource {
	private final String prefix;

	protected AbstractLocalizationSource(String prefix) {
		this.prefix = prefix;
	}

	/**
	 * @see org.geoscheduler.commons.i18n.LocalizationSource#translate(java.lang.String,
	 *      java.util.Locale)
	 */
	public String translate(String key, Locale locale, Object... params) {
		return translate(key, "[" + key + "]", locale,params);
	}

	/**
	 * @see org.geoscheduler.commons.i18n.LocalizationSource#translate(java.lang.String,
	 *      java.util.Locale, java.lang.String)
	 */
	public String translate(String key, String defValue, Locale locale, Object... params) {
		try {
			ResourceBundle bundle = getResourceBundle(AssertTools.assertNotNull(locale, "locale is null"));
			key = StringTools.isEmpty(prefix) ? key : prefix + key;
			return MessageFormat.format((bundle != null ? bundle.getString(key) : defValue), params);
		} catch (MissingResourceException ex) {
			return defValue;
		} catch (NullPointerException ex) {
			throw new IllegalArgumentException("Key is null", ex);
		} catch (ClassCastException ex) {
			throw new IllegalStateException("Value is not String", ex);
		}
	}

	/** Provides resource bundle for {@param locale} */
	protected abstract ResourceBundle getResourceBundle(Locale locale);
}
